from util.myredis import r
from views.base import BaseHandler
import json
from db import db
from util.myjwt import myjwt
import time
from util.comm import md5


# 权限验证装饰器:两类接口共100个，50个读的，50个接口，读取的接口操作完跳转到a.html页面，写的接口跳转到b.html页面
# def pomition():
#     def is_login(func):
#         def wrapper(self,*args,**kargs):
#             #业务
#             #获取token
#             headers = self.request.headers
#             try:
#                 token = headers['token']
#                 print("token>>>>>>>>>>>>>>>",token)
#                 flag = myjwt.check(token)
#                 if flag == True:
#                     #解析验证时间
#                     payload = myjwt.jwt_decode(token)
#                     print("payload",payload)
#                     # 获取过期时间
#                     ptime = payload['data']['exptime']
#                     userid = payload['data']['userid']
#                     now = time.time()
#                     # 判断是否过期
#                     if int(now)-int(ptime)>3600:
#                         return self.finish({"code":402,"msg":"token过期"})
#                     #  {"data": {"name": "zs", "userid": 1,'exp':}}
#                     urls = r.list_pop("keys"+ str(userid))
#                     print("urls",urls)
#                     url = self.request.uri
#                     print("url",url)
#                     if url not in urls.decode():
#                         return self.finish({"code": 400, "msg": "无权访问"})
#                 else:
#                     return self.finish({"code":403,"msg":"token错误"})
#             except Exception as a:
#                 print("a",a)
#                 return self.finish({"code":401,"msg":"错误"})
# 验证token
# headers['token']
# 解析获取时间和当前时间对比
#         func(self,*args,**kargs)
#     return wrapper
# return is_login
# 权限验证装饰器:两类接口共100个，50个读的，50个接口，读取的接口操作完跳转到百度页面，写的接口跳转到淘宝页面
# 装饰器传参
def aa(type):
    def bb(func):
        def cc(self):
            func(self)
            if type == 1:
                self.redirect("https://www.baidu.com/")
            else:
                self.redirect("https://www.taobao.com/")

        return cc

    return bb


# 装饰器不传参
def add():
    def acc(func):
        def abb(self):
            pytime = int(time.time())
            func(self)
            ontime = int(time.time())
            times = ontime - pytime
            print("此接口执行用了》》》", times)

        return abb

    return acc


class UserHandler(BaseHandler):
    @aa(1)
    # @add()
    def get(self):
        time.sleep(5)
        # 获取参数
        # name = self.get_query_argument("name")
        # password = self.get_query_argument("password")
        # # self.write("name is :"+name+",password is:"+password)
        # self.write(json.dumps({"id":1}))
        self.write("34234234")

    @aa(2)
    def post(self):
        data = json.loads(self.request.body)
        id = data['id']
        name = data['name']

        self.write("name 23is post:" + str(id) + ",password is:" + name)


# 通过角色id获取资源列表的方法
def getMenu(roleid):
    sql = "select res.*,pres.name as pname from role_resource as rr left join resource as res on rr.resourceid=res.id  inner join resource as pres on res.pid=pres.id where rr.userid=%d" % (
        int(roleid))
    res = db.findAll(sql)
    reslist = []
    ids = []
    myurl = []
    # 遍历查询结果
    for i in res:
        myurl.append(i['url'])
        # 判断父类是否存在，不存在添加
        if i["pid"] not in ids:
            ids.append(i['pid'])
            reslist.append(
                {"id": i["pid"], "name": i['pname'], "son": [{"id": i['id'], "name": i['name'], 'url': i['url']}]})
        else:
            # 存在，查找父类，遍历父类用子类的pid对比
            for (index, p) in enumerate(reslist):
                if i['pid'] == p['id']:
                    # 将子类加到父类下
                    reslist[index]['son'].append({"id": i['id'], "name": i['name'], 'url': i['url']})
    return reslist, myurl


class Login(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        username = data["username"]
        pwd = data["password"]
        password = md5(pwd)
        # 判断是否为空
        if not all([username, password]):
            self.finish({"code": 400, "msg": "必须输入账号或密码"})
        # 查询用户是否存在
        sql = "select * from admin_user where username='%s'" % username
        res = db.findone(sql)
        if res:
            if password != res["password"]:
                self.finish({"code": 400, "msg": "密码错误"})
            else:
                jwt = {"data": {"userid": res["id"], "roleid": res["roleid"], "name": res["username"],
                                "exptime": int(time.time())}}
                token = myjwt.jwt_encode(jwt)
                # 获取角色id获取资源列表的方法
                menulist, myurl = getMenu(res['roleid'])
                print("资源权限>>>>",myurl)
                # 当前角色接口权限
                list = prepare(res["roleid"])
                print("接口权限>>>>>>", list)
                r.str_add("keys" + str(res["id"]), json.dumps(list))
                self.finish({"code": 200, "msg": "登录成功", "userid": res["id"], "roleid": res["roleid"], "token": token,
                             "data": menulist, 'mpstatus': res['mpstatus'], 'name': res['name'], 'myurl': myurl})
        else:
            self.finish({"code": 400, "msg": "用户不存在"})


def prepare(roleid):
    sql = "select res.url from role_resource as rr left join resource as res on rr.resourceid=res.id where rr.userid=%d and res.type=2" % int(
        roleid)
    res = db.findAll(sql)
    lst = []
    for i in res:
        lst.append(i["url"])
    return lst


# 左边栏
# class getMenu(BaseHandler):
#     def get(self):
#         roleid = self.get_query_argument("roleid")
#         sql = "select re.*,pre.name as pname from role_resource as rr left join resource as re on rr.resourceid=re.id left join resource as pre on pre.id = re.pid where rr.userid=%d"%int(roleid)
#         res = db.findAll(sql)
#         # 新建list=[],遍历列表res，将父类放入List列表中
#         list = []
#         idlist = []
#         for i in res:
#             if i["pid"] not in idlist:
#                 list.append({"id": i["pid"], "name": i["pname"], "son":[]})
#                 idlist.append(i["pid"])
#         # 遍历res,把出子类和父类list进行对比，如果相同放到son,son.append
#         for j in res:
#             for index,p in enumerate(list):
#                 if j['pid'] == p['id']:
#                     list[index]['son'].append({"id":j['id'],"name":j['name'],'url':j['url']})
#         self.finish({"code":200,'list':list})

# 添加用户
class register(BaseHandler):
    # @pomition()
    def post(self):
        data = json.loads(self.request.body)
        username = data["username"]
        # print("username", username)
        pwd = '123456'
        password = md5(pwd)
        roleid = data["value"]
        name = data["name"]
        # 判断是否为空
        if not all([username, password, roleid, name]):
            self.finish({"code": 10010, "msg": "不能为空"})
        else:
            sql = "select * from admin_user where username='%s'" % (username)
            res = db.findone(sql)
            if res:
                self.finish({"code": 400, "msg": "用户已存在"})
            sql = "insert into admin_user(name,username,password,roleid) values ('%s','%s','%s',%d)" % (
            name, username, password, int(roleid))
            db.add(sql)
            db.commit()
            self.finish({"code": 200, "msg": "添加用户成功"})

    # 获取全部角色
    def get(self):
        sql = "select * from roles"
        res = db.findAll(sql)
        self.finish({"code": 200, "msg": "获取成功", "data": res})


# 修改密码      
class upduser(BaseHandler):
    # @pomition()
    # 修改密码
    def post(self):
        data = json.loads(self.request.body)
        pwd = data["pwd"]
        pwds = data["pwds"]
        userid = data["userid"]
        # print(pwd)
        if not all([pwd, pwds, userid]):
            self.write({"code": 400, "msg": "字段不能为空"})
        else:
            password = md5(pwd)
            sql = "select * from admin_user where id=%d" % (int(userid))
            res = db.findone(sql)
            if res:
                if res["password"] != password:
                    self.write({"code": 400, "msg": "旧密码错误"})
                else:
                    pwds1 = md5(pwds)
                    if pwds1 != res["password"]:
                        sql1 = "update admin_user set password='%s', mpstatus=2 where id = %d" % (pwds1, int(userid))
                        db.add(sql1)
                        db.commit()
                        self.write({"code": 200, "msg": "修改密码成功"})
                    else:
                        self.write({"code": 400, "msg": "新旧密码一致"})
            else:
                self.write({"code": 400, "msg": "用户不存在"})


# 退出
class Exit(BaseHandler):
    def get(self):
        # 获取token
        token = self.request.headers['token']
        # print("token",token)
        key = 'logout'
        # 加入延时队列
        r.sortedset_add(key, token, int(time.time()))
        self.write({"code": 200, "msg": '退出成功'})


